package com.yc.filter;

import com.yc.service.UserBiz;
import com.yc.uitls.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author zwei
 * @create 2024-09-05 9:58
 */
//此锅炉器作用   1.是否有token 2.token是否过期 3.验证用户名和密码是否匹配
@Component
@Slf4j
public class JWTFilter extends OncePerRequestFilter {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserBiz resuserBiz;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken=request.getHeader("token"); //从请求头中获取token
        if (jwtToken!=null&&!jwtToken.isEmpty()&&!jwtTokenUtil.isTokenExpired(jwtToken)){
            try {       //token可用
                Claims claims=jwtTokenUtil.decodeJWTWithkey(jwtToken);
                String username= (String) claims.get("username");
                UserDetails user=((UserDetailsService)resuserBiz).loadUserByUsername(username);
                if (user!=null){
                    //验证密码与权限是否正确
                    UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(
                            user,null,user.getAuthorities()
                    );
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }else {
            log.warn("token is null or empty or out of time,probable user is not log in! ");
        }
        filterChain.doFilter(request,response); //继续过滤
    }
}
